<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexedDB数据导入转换工具</title>
    <!-- 引入JSZip库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"], input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .status {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
        .warning {
            background-color: #fff3cd;
            color: #856404;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
            max-height: 300px;
            overflow-y: auto;
        }
        .json-viewer {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            border: 1px solid #ddd;
        }
        .log-container {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 10px;
            height: 200px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 14px;
            margin-top: 20px;
        }
        .log-entry {
            margin: 5px 0;
            padding: 3px 0;
            border-bottom: 1px dashed #ddd;
        }
        .log-time {
            color: #6c757d;
            margin-right: 8px;
        }
        .download-btn {
            background-color: #007bff;
        }
        .download-btn:hover {
            background-color: #0069d9;
        }
        .preview-btn {
            background-color: #6c757d;
        }
        .preview-btn:hover {
            background-color: #5a6268;
        }
        .converted-data {
            margin-top: 20px;
        }
        .tab-container {
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }
        .tab-buttons {
            background-color: #f8f9fa;
            display: flex;
            border-bottom: 1px solid #ddd;
        }
        .tab-button {
            padding: 10px 15px;
            border: none;
            background-color: transparent;
            cursor: pointer;
            color: #333;
            font-weight: bold;
        }
        .tab-button.active {
            background-color: #e9ecef;
            border-bottom: 2px solid #4CAF50;
        }
        .tab-content {
            padding: 15px;
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .stat-item {
            margin-bottom: 5px;
            padding: 5px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h1>IndexedDB数据导入转换工具</h1>
    
    <div class="card">
        <h2>文件上传</h2>
        <div class="form-group">
            <label for="jsonFile">选择IndexedDB导出的JSON文件</label>
            <input type="file" id="jsonFile" accept=".json">
            <div class="form-actions" style="margin-top: 10px;">
                <button id="uploadBtn" class="preview-btn">预览JSON数据</button>
                <button id="convertBtn" disabled>转换数据结构</button>
                <button id="downloadBtn" class="download-btn" disabled>下载ZIP文件</button>
                <button id="downloadSingleBtn" class="download-btn" disabled>下载单个文件</button>
            </div>
        </div>
    </div>
    
    <div class="tab-container">
        <div class="tab-buttons">
            <button class="tab-button active" data-tab="source">源数据</button>
            <button class="tab-button" data-tab="stats">数据统计</button>
            <button class="tab-button" data-tab="converted">转换结果</button>
        </div>
        
        <div class="tab-content active" id="source-tab">
            <div id="jsonPreview" class="json-viewer">
                <p>请上传JSON文件并点击"预览JSON数据"按钮</p>
            </div>
        </div>
        
        <div class="tab-content" id="stats-tab">
            <div id="dataStats">
                <p>尚未加载数据</p>
            </div>
        </div>
        
        <div class="tab-content" id="converted-tab">
            <div class="converted-data">
                <div id="convertedPreview" class="json-viewer">
                    <p>请先转换数据</p>
                </div>
                <div id="fileList" style="margin-top: 20px; display: none;">
                    <h4>已生成的文件列表</h4>
                    <ul id="fileListItems"></ul>
                </div>
            </div>
        </div>
    </div>
    
    <div class="log-container" id="logContainer">
        <div class="log-entry">
            <span class="log-time">[00:00:00]</span>准备就绪，等待上传JSON文件...
        </div>
    </div>
    
    <div id="statusContainer"></div>
    
    <script>
        // 全局变量
        let sourceData = null;
        let convertedData = null;
        let jsonFiles = null;
        
        // DOM元素
        const jsonFileInput = document.getElementById('jsonFile');
        const uploadBtn = document.getElementById('uploadBtn');
        const convertBtn = document.getElementById('convertBtn');
        const downloadBtn = document.getElementById('downloadBtn');
        const downloadSingleBtn = document.getElementById('downloadSingleBtn');
        const jsonPreview = document.getElementById('jsonPreview');
        const convertedPreview = document.getElementById('convertedPreview');
        const dataStats = document.getElementById('dataStats');
        const statusContainer = document.getElementById('statusContainer');
        const logContainer = document.getElementById('logContainer');
        const fileList = document.getElementById('fileList');
        const fileListItems = document.getElementById('fileListItems');
        
        // 标签页相关
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');
        
        // 标签页切换
        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const tabName = button.getAttribute('data-tab');
                
                // 更新标签按钮状态
                tabButtons.forEach(btn => {
                    btn.classList.remove('active');
                });
                button.classList.add('active');
                
                // 更新标签内容显示
                tabContents.forEach(content => {
                    content.classList.remove('active');
                });
                document.getElementById(`${tabName}-tab`).classList.add('active');
            });
        });
        
        // 添加日志条目
        function addLog(message) {
            const now = new Date();
            const timeStr = now.toTimeString().split(' ')[0];
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = `<span class="log-time">[${timeStr}]</span>${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        // 更新状态
        function updateStatus(message, type = 'info') {
            statusContainer.innerHTML = `<div class="status ${type}">${message}</div>`;
        }
        
        // 文件上传和预览逻辑
        uploadBtn.addEventListener('click', () => {
            const file = jsonFileInput.files[0];
            if (!file) {
                updateStatus('请先选择JSON文件', 'error');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    sourceData = JSON.parse(event.target.result);
                    
                    // 检查是否存在questionBank结构并提取
                    if (sourceData.questionBank) {
                        addLog('检测到questionBank结构，提取数据');
                        sourceData = sourceData.questionBank;
                    }
                    
                    // 预览数据（限制大小以防止浏览器崩溃）
                    const previewText = JSON.stringify(sourceData, null, 2);
                    jsonPreview.innerHTML = `<pre>${previewText.length > 10000 ? previewText.substring(0, 10000) + '\n... (数据太大，仅显示部分)' : previewText}</pre>`;
                    
                    // 显示数据统计
                    updateDataStats(sourceData);
                    
                    // 启用转换按钮
                    convertBtn.disabled = false;
                    
                    addLog(`成功加载JSON文件: ${file.name} (${formatFileSize(file.size)})`);
                    updateStatus('JSON文件加载成功，可以进行转换操作', 'success');
                    
                    // 切换到数据统计标签
                    tabButtons.forEach(btn => {
                        btn.classList.remove('active');
                        if (btn.getAttribute('data-tab') === 'stats') {
                            btn.classList.add('active');
                        }
                    });
                    
                    tabContents.forEach(content => {
                        content.classList.remove('active');
                    });
                    document.getElementById('stats-tab').classList.add('active');
                    
                } catch (error) {
                    updateStatus(`JSON解析失败: ${error.message}`, 'error');
                    addLog(`JSON解析失败: ${error.message}`);
                    jsonPreview.innerHTML = '<p>JSON解析失败，请检查文件格式</p>';
                }
            };
            
            reader.onerror = () => {
                updateStatus('文件读取失败', 'error');
                addLog('文件读取失败');
            };
            
            reader.readAsText(file);
        });
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes < 1024) {
                return bytes + ' bytes';
            } else if (bytes < 1024 * 1024) {
                return (bytes / 1024).toFixed(2) + ' KB';
            } else {
                return (bytes / 1024 / 1024).toFixed(2) + ' MB';
            }
        }
        
        // 更新数据统计
        function updateDataStats(data) {
            if (!data) {
                dataStats.innerHTML = '<p>尚未加载数据</p>';
                return;
            }
            
            let statsHtml = '<h3>数据统计</h3>';
            
            try {
                // 提取数据
                let papers = [];
                let questions = [];
                let config = {};
                
                // 尝试各种可能的数据结构
                if (data.papers && Array.isArray(data.papers)) {
                    papers = data.papers;
                    statsHtml += `<div class="stat-item">数据格式: 包含papers数组</div>`;
                }
                
                if (data.questions && Array.isArray(data.questions)) {
                    questions = data.questions;
                    statsHtml += `<div class="stat-item">数据格式: 包含questions数组</div>`;
                }
                
                if (data.config) {
                    if (Array.isArray(data.config)) {
                        // config是数组，尝试转换为对象
                        data.config.forEach(item => {
                            if (item && item.id && item.data) {
                                config[item.id] = item.data;
                            }
                        });
                        statsHtml += `<div class="stat-item">config格式: 数组形式 (已转换为对象)</div>`;
                    } else if (typeof data.config === 'object') {
                        config = data.config;
                        statsHtml += `<div class="stat-item">config格式: 对象形式</div>`;
                    }
                }
                
                // 特殊情况：如果是questionBank结构但未事先处理
                if (data.questionBank) {
                    const qb = data.questionBank;
                    if (qb.papers && Array.isArray(qb.papers)) {
                        papers = qb.papers;
                        statsHtml += `<div class="stat-item">从questionBank中提取papers数组</div>`;
                    }
                    if (qb.questions && Array.isArray(qb.questions)) {
                        questions = qb.questions;
                        statsHtml += `<div class="stat-item">从questionBank中提取questions数组</div>`;
                    }
                    if (qb.config) {
                        if (Array.isArray(qb.config)) {
                            // config是数组，尝试转换为对象
                            qb.config.forEach(item => {
                                if (item && item.id && item.data) {
                                    config[item.id] = item.data;
                                }
                            });
                            statsHtml += `<div class="stat-item">从questionBank中提取config (数组形式)</div>`;
                        } else if (typeof qb.config === 'object') {
                            config = qb.config;
                            statsHtml += `<div class="stat-item">从questionBank中提取config (对象形式)</div>`;
                        }
                    }
                }
                
                // 显示基本统计信息
                statsHtml += `<div class="stat-item">试卷数量: ${papers.length}</div>`;
                statsHtml += `<div class="stat-item">题目总数: ${questions.length}</div>`;
                statsHtml += `<div class="stat-item">配置项数量: ${Object.keys(config).length}</div>`;
                
                // 显示数据库信息（如果有）
                if (data.database) {
                    statsHtml += `<div class="stat-item">数据库名称: ${data.database}</div>`;
                }
                if (data.version) {
                    statsHtml += `<div class="stat-item">数据库版本: ${data.version}</div>`;
                }
                if (data.timestamp) {
                    statsHtml += `<div class="stat-item">数据导出时间: ${new Date(data.timestamp).toLocaleString()}</div>`;
                }
                
                // 显示试卷列表
                if (papers.length > 0) {
                    statsHtml += '<h4>试卷列表</h4>';
                    statsHtml += '<ul>';
                    
                    for (const paper of papers) {
                        const questionCount = paper.questionIds ? paper.questionIds.length : 0;
                        statsHtml += `<li>${paper.name || '未命名'} (ID: ${paper.id || '无ID'}) - ${questionCount} 个题目</li>`;
                    }
                    
                    statsHtml += '</ul>';
                }
                
                // 显示配置项
                if (Object.keys(config).length > 0) {
                    statsHtml += '<h4>配置项</h4>';
                    statsHtml += '<ul>';
                    
                    for (const key in config) {
                        let configValue = config[key];
                        let displayValue = '';
                        
                        if (typeof configValue === 'object') {
                            displayValue = '对象';
                        } else if (typeof configValue === 'string' && configValue.length > 50) {
                            displayValue = configValue.substring(0, 50) + '...';
                        } else {
                            displayValue = String(configValue);
                        }
                        
                        statsHtml += `<li>${key}: ${displayValue}</li>`;
                    }
                    
                    statsHtml += '</ul>';
                }
                
                // 如果没有识别到任何数据
                if (papers.length === 0 && questions.length === 0 && Object.keys(config).length === 0) {
                    statsHtml += '<div class="stat-item warning">警告：未识别到试卷或题目数据</div>';
                    statsHtml += '<div class="stat-item">请检查JSON结构是否符合要求，或者联系开发者添加支持</div>';
                    
                    // 显示顶层数据结构
                    statsHtml += '<h4>数据结构预览</h4>';
                    statsHtml += '<ul>';
                    
                    for (const key in data) {
                        if (data.hasOwnProperty(key)) {
                            const value = data[key];
                            const type = Array.isArray(value) ? `数组 (${value.length} 项)` : 
                                  typeof value === 'object' && value !== null ? '对象' : typeof value;
                            
                            statsHtml += `<li>${key}: ${type}</li>`;
                        }
                    }
                    
                    statsHtml += '</ul>';
                }
            } catch (e) {
                statsHtml += `<div class="stat-item error">数据分析出错: ${e.message}</div>`;
                console.error('数据分析出错:', e);
            }
            
            dataStats.innerHTML = statsHtml;
        }
        
        // 转换题目格式
        function convertQuestionFormat(oldQuestion, starsConfig) {
            // 创建新题目对象（保留原始ID）
            const newQuestion = {
                id: oldQuestion.id,
                detail: [],
                answer: oldQuestion.answer || "",
                simpleAnswer: oldQuestion.simpleAnswer || "",
                keywords: oldQuestion.keywords || [],
                stars: 0 // 默认为0，后面会尝试从starsConfig中获取
            };
            
            // 从stars配置中获取星标值
            if (starsConfig && typeof starsConfig === 'object' && starsConfig[oldQuestion.id]) {
                newQuestion.stars = starsConfig[oldQuestion.id];
            } else if (oldQuestion.stars !== undefined) {
                // 如果题目本身有stars属性，则使用
                newQuestion.stars = oldQuestion.stars;
            }
            
            // 如果旧题目使用title和options格式，转换为detail数组
            if (oldQuestion.title || (oldQuestion.options && Array.isArray(oldQuestion.options))) {
                // 添加题干
                if (oldQuestion.title) {
                    newQuestion.detail.push('题干');
                    newQuestion.detail.push(oldQuestion.title);
                }
                
                // 添加选项
                if (Array.isArray(oldQuestion.options)) {
                    for (const option of oldQuestion.options) {
                        newQuestion.detail.push('选项');
                        newQuestion.detail.push(option);
                    }
                }
            } else if (Array.isArray(oldQuestion.detail)) {
                // 如果已经是detail格式，直接使用
                newQuestion.detail = [...oldQuestion.detail];
            }
            
            return newQuestion;
        }
        
        // 转换数据格式
        function convertDataFormat(oldData) {
            try {
                addLog('开始转换数据格式...');
                
                // 检查是否存在questionBank结构并提取
                if (oldData.questionBank) {
                    addLog('检测到questionBank结构，提取数据');
                    oldData = oldData.questionBank;
                }
                
                // 提取试卷
                if (oldData.papers && Array.isArray(oldData.papers)) {
                    papers = oldData.papers;
                    addLog(`提取到 ${papers.length} 个试卷`);
                }
                
                // 提取题目
                if (oldData.questions && Array.isArray(oldData.questions)) {
                    questions = oldData.questions;
                    addLog(`提取到 ${questions.length} 个题目`);
                }
                
                // 提取配置
                let config = {};
                let starsConfig = {};
                
                if (oldData.config) {
                    if (Array.isArray(oldData.config)) {
                        // config是数组，尝试转换为对象
                        oldData.config.forEach(item => {
                            if (item && item.id && item.data) {
                                config[item.id] = item.data;
                                addLog(`从config数组中提取配置项: ${item.id}`);
                                
                                // 特别处理stars配置
                                if (item.id === 'stars') {
                                    starsConfig = item.data;
                                    addLog(`提取到stars配置，共有 ${Object.keys(starsConfig).length} 个星标记录`);
                                }
                            }
                        });
                    } else if (typeof oldData.config === 'object') {
                        config = oldData.config;
                        addLog('提取到config对象');
                        
                        // 检查是否有stars配置
                        if (config.stars) {
                            starsConfig = config.stars;
                            addLog(`从config对象中提取stars配置，共有 ${Object.keys(starsConfig).length} 个星标记录`);
                        }
                    }
                }
                
                // 验证数据是否有效
                if (papers.length === 0) {
                    addLog('警告: 未找到试卷数据，将创建一个默认试卷');
                    papers = [{ id: 'default', name: '默认试卷', questionIds: [] }];
                }
                
                if (questions.length === 0) {
                    addLog('警告: 未找到题目数据');
                }
                
                // 为没有questionIds的试卷创建空数组
                papers.forEach(paper => {
                    if (!paper.questionIds) {
                        paper.questionIds = [];
                        addLog(`为试卷 "${paper.name}" 创建空的questionIds数组`);
                    }
                });
                
                // 如果有题目但没有分配到试卷，将其分配到默认试卷
                if (questions.length > 0) {
                    let assignedQuestionIds = new Set();
                    papers.forEach(paper => {
                        paper.questionIds.forEach(id => assignedQuestionIds.add(id));
                    });
                    
                    const unassignedQuestions = questions.filter(q => !assignedQuestionIds.has(q.id));
                    if (unassignedQuestions.length > 0) {
                        const defaultPaper = papers.find(p => p.id === 'default') || papers[0];
                        addLog(`发现 ${unassignedQuestions.length} 个未分配的题目，添加到 "${defaultPaper.name}" 试卷`);
                        unassignedQuestions.forEach(q => {
                            if (!defaultPaper.questionIds.includes(q.id)) {
                                defaultPaper.questionIds.push(q.id);
                            }
                        });
                    }
                }
                
                // 初始化新数据结构
                const newData = {
                    config: {
                        papers: {}, // 将存储试卷映射 {paperId: paperName}
                        sync_config: config.sync_config || {},
                        prompt_config: config.service_config || config.prompt_config || {}
                    },
                    paperStores: {} // 每个试卷的题目集合 {paperId: [questions]}
                };
                
                // 1. 构建papers映射
                const papersMap = {};
                for (const paper of papers) {
                    papersMap[paper.id] = paper.name;
                }
                newData.config.papers = papersMap;
                addLog(`转换了 ${papers.length} 个试卷的映射关系`);
                
                // 2. 构建试卷与题目的关系
                for (const paper of papers) {
                    // 获取该试卷下的所有题目ID
                    const paperQuestionIds = paper.questionIds || [];
                    
                    // 创建该试卷的题目集合
                    const paperQuestions = [];
                    
                    // 跟踪星标题目数量
                    let starredCount = 0;
                    
                    // 根据题目ID找到对应的题目
                    for (const qId of paperQuestionIds) {
                        const question = questions.find(q => q.id === qId);
                        if (question) {
                            // 转换题目格式（如果需要），同时传入starsConfig
                            const convertedQuestion = convertQuestionFormat(question, starsConfig);
                            paperQuestions.push(convertedQuestion);
                            
                            // 统计星标题目
                            if (convertedQuestion.stars > 0) {
                                starredCount++;
                            }
                        }
                    }
                    
                    addLog(`处理试卷 "${paper.name}" (ID: ${paper.id}): ${paperQuestions.length} 个题目，其中 ${starredCount} 个星标题目`);
                    
                    // 存储该试卷的题目集合
                    newData.paperStores[paper.id] = paperQuestions;
                }
                
                // 3. 保留其他config配置项
                for (const key in config) {
                    if (key !== 'papers' && key !== 'sync_config' && key !== 'service_config' && key !== 'prompt_config' && key !== 'stars') {
                        newData.config[key] = config[key];
                    }
                }
                
                // 将stars配置保存到新配置中
                if (Object.keys(starsConfig).length > 0) {
                    newData.config.stars = starsConfig;
                    addLog('保留stars配置到新数据结构');
                }
                
                // 如果有试卷更新时间信息，保留
                if (config.papers_update_time) {
                    newData.config.papers_update_time = config.papers_update_time;
                }
                
                addLog('数据格式转换完成');
                
                return newData;
            } catch (error) {
                console.error('转换数据格式失败:', error);
                addLog(`转换数据格式失败: ${error.message}`);
                throw error;
            }
        }
        
        // 创建JSON文件
        function createJsonFiles(newData) {
            try {
                addLog('开始创建JSON文件...');
                
                const files = [];
                const currentTimestamp = Date.now();
                
                // 1. 创建config.json
                const configJson = {
                    timestamp: currentTimestamp,
                    service_config: newData.config.prompt_config || {},
                    papers: newData.config.papers || {},  // 试卷映射
                    papers_update_time: {},  // 将使用当前时间戳
                    sync_config: newData.config.sync_config || {}  // 同步配置
                };
                
                // 为所有试卷设置当前的更新时间
                for (const paperId in newData.config.papers) {
                    configJson.papers_update_time[paperId] = currentTimestamp;
                }
                
                addLog('已将所有试卷的更新时间设置为当前时间戳');
                
                files.push({
                    fileName: 'config.json',
                    content: JSON.stringify(configJson, null, 2)
                });
                
                addLog('已创建 config.json 文件');
                
                // 2. 为每个试卷创建JSON文件
                for (const paperId in newData.paperStores) {
                    const paperQuestions = newData.paperStores[paperId];
                    const paperName = newData.config.papers[paperId] || '未命名试卷';
                    
                    const paperJson = {
                        timestamp: currentTimestamp,
                        paper: {
                            id: paperId,
                            name: paperName
                        },
                        questions: paperQuestions
                    };
                    
                    files.push({
                        fileName: `paper_${paperId}.json`,
                        content: JSON.stringify(paperJson, null, 2)
                    });
                    
                    addLog(`已创建 paper_${paperId}.json 文件 (${paperQuestions.length} 个题目)`);
                }
                
                addLog(`共创建了 ${files.length} 个JSON文件`);
                
                return files;
            } catch (error) {
                console.error('创建JSON文件失败:', error);
                addLog(`创建JSON文件失败: ${error.message}`);
                throw error;
            }
        }
        
        // 转换按钮点击事件
        convertBtn.addEventListener('click', async () => {
            if (!sourceData) {
                updateStatus('请先上传并预览JSON数据', 'error');
                return;
            }
            
            try {
                // 转换数据
                convertedData = convertDataFormat(sourceData);
                
                // 创建JSON文件
                jsonFiles = createJsonFiles(convertedData);
                
                // 预览转换结果的第一个文件
                if (jsonFiles && jsonFiles.length > 0) {
                    const configFile = jsonFiles.find(f => f.fileName === 'config.json');
                    
                    if (configFile) {
                        const previewContent = `<h4>config.json</h4><pre>${configFile.content}</pre>`;
                        convertedPreview.innerHTML = previewContent;
                    } else {
                        convertedPreview.innerHTML = `<pre>${jsonFiles[0].content}</pre>`;
                    }

                    // 显示文件列表
                    fileList.style.display = 'block';
                    fileListItems.innerHTML = '';
                    
                    jsonFiles.forEach((file, index) => {
                        const li = document.createElement('li');
                        li.innerHTML = `<span>${file.fileName}</span> <button class="download-single-file" data-index="${index}">下载</button>`;
                        fileListItems.appendChild(li);
                    });
                    
                    // 为每个文件的下载按钮添加事件
                    document.querySelectorAll('.download-single-file').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const fileIndex = parseInt(this.getAttribute('data-index'));
                            downloadSingleFile(fileIndex);
                        });
                    });
                }
                
                // 启用下载按钮
                downloadBtn.disabled = false;
                downloadSingleBtn.disabled = false;
                
                // 切换到转换结果标签页
                tabButtons.forEach(btn => {
                    btn.classList.remove('active');
                    if (btn.getAttribute('data-tab') === 'converted') {
                        btn.classList.add('active');
                    }
                });
                
                tabContents.forEach(content => {
                    content.classList.remove('active');
                });
                document.getElementById('converted-tab').classList.add('active');
                
                updateStatus('数据转换成功，可以下载结果', 'success');
            } catch (error) {
                updateStatus(`数据转换失败: ${error.message}`, 'error');
            }
        });
        
        // 下载单个文件
        function downloadSingleFile(fileIndex) {
            if (!jsonFiles || jsonFiles.length === 0 || fileIndex >= jsonFiles.length) {
                updateStatus('没有可下载的文件', 'error');
                return;
            }
            
            const file = jsonFiles[fileIndex];
            const blob = new Blob([file.content], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = file.fileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            addLog(`已下载: ${file.fileName}`);
        }
        
        // 下载单个文件按钮的事件处理
        downloadSingleBtn.addEventListener('click', () => {
            if (!jsonFiles || jsonFiles.length === 0) {
                updateStatus('没有可下载的转换结果', 'error');
                return;
            }
            
            // 显示文件选择对话框
            const selector = document.createElement('div');
            selector.className = 'file-selector';
            selector.innerHTML = `
                <div style="background: rgba(0,0,0,0.5); position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1000; display: flex; justify-content: center; align-items: center;">
                    <div style="background: white; padding: 20px; border-radius: 8px; max-width: 80%; max-height: 80%; overflow: auto;">
                        <h3>选择要下载的文件</h3>
                        <ul style="list-style: none; padding: 0;">
                            ${jsonFiles.map((file, index) => `
                                <li style="margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                                    <label>
                                        <input type="radio" name="fileToDownload" value="${index}"> 
                                        ${file.fileName} (${(file.content.length / 1024).toFixed(2)} KB)
                                    </label>
                                </li>
                            `).join('')}
                        </ul>
                        <div style="margin-top: 20px; text-align: right;">
                            <button id="cancelFileSelection" style="margin-right: 10px; padding: 5px 10px;">取消</button>
                            <button id="confirmFileSelection" style="padding: 5px 10px; background: #4CAF50; color: white; border: none; border-radius: 4px;">下载</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(selector);
            
            // 取消按钮
            document.getElementById('cancelFileSelection').addEventListener('click', () => {
                document.body.removeChild(selector);
            });
            
            // 确认按钮
            document.getElementById('confirmFileSelection').addEventListener('click', () => {
                const selected = document.querySelector('input[name="fileToDownload"]:checked');
                if (selected) {
                    const fileIndex = parseInt(selected.value);
                    downloadSingleFile(fileIndex);
                    document.body.removeChild(selector);
                } else {
                    alert('请选择要下载的文件');
                }
            });
        });
        
        // 下载ZIP文件
        downloadBtn.addEventListener('click', async () => {
            if (!jsonFiles || jsonFiles.length === 0) {
                updateStatus('没有可下载的转换结果', 'error');
                return;
            }
            
            try {
                addLog('正在创建ZIP文件...');
                
                // 创建一个新的JSZip实例
                const zip = new JSZip();
                
                // 将每个JSON文件添加到ZIP中
                jsonFiles.forEach(file => {
                    zip.file(file.fileName, file.content);
                });
                
                // 生成ZIP文件
                const zipBlob = await zip.generateAsync({
                    type: 'blob',
                    compression: 'DEFLATE',
                    compressionOptions: {
                        level: 9
                    }
                });
                
                // 创建下载链接
                const now = new Date();
                const dateStr = now.toISOString().split('T')[0];
                const fileName = `converted_data_${dateStr}.zip`;
                
                const url = URL.createObjectURL(zipBlob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                addLog(`ZIP文件已下载: ${fileName}`);
                updateStatus('ZIP文件已下载', 'success');
            } catch (error) {
                console.error('创建ZIP文件失败:', error);
                addLog(`创建ZIP文件失败: ${error.message}`);
                updateStatus(`创建ZIP文件失败: ${error.message}`, 'error');
                
                // 如果创建ZIP失败，则提供原始的合并JSON下载
                try {
                    const allFiles = {
                        timestamp: Date.now(),
                        files: jsonFiles.map(file => ({
                            fileName: file.fileName,
                            content: JSON.parse(file.content)
                        }))
                    };
                    
                    const blob = new Blob([JSON.stringify(allFiles)], { type: 'application/json' });
                    const url = URL.createObjectURL(blob);
                    
                    const now = new Date();
                    const dateStr = now.toISOString().split('T')[0];
                    const fileName = `converted_data_${dateStr}.json`;
                    
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    
                    addLog(`作为单个JSON文件下载: ${fileName}`);
                } catch (fallbackError) {
                    console.error('备用下载也失败:', fallbackError);
                    addLog(`备用下载失败: ${fallbackError.message}`);
                }
            }
        });
    </script>
</body>
</html> 